<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="190px"
      max-height="500px"
      v-loading="formLoading"
    >
      <el-form-item label="客户端编号" prop="clientId">
        <el-input v-model="formData.clientId" placeholder="请输入客户端编号" />
      </el-form-item>
      <el-form-item label="客户端密钥" prop="secret">
        <el-input v-model="formData.secret" placeholder="请输入客户端密钥" />
      </el-form-item>
      <el-form-item label="应用名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入应用名" />
      </el-form-item>
      <el-form-item label="应用图标" prop="logo">
        <UploadImg v-model="formData.logo" width="100px" height="100px" />
      </el-form-item>
      <el-form-item label="应用描述" prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入应用描述" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in common_enable_status" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="accessTokenValiditySeconds">
        <template #label>
          <span>
            访问令牌的有效期
            <el-tooltip content="默认30分钟" placement="top">
              <Icon icon="ep:question-filled" />
            </el-tooltip>
          </span>
        </template>
        <el-input-number v-model="formData.accessTokenValiditySeconds" placeholder="单位：秒" />
      </el-form-item>
      <el-form-item prop="refreshTokenValiditySeconds">
        <template #label>
          <span>
            刷新令牌的有效期
            <el-tooltip content="默认30天" placement="top">
              <Icon icon="ep:question-filled" />
            </el-tooltip>
          </span>
        </template>
        <el-input-number v-model="formData.refreshTokenValiditySeconds" placeholder="单位：秒" />
      </el-form-item>
      <el-form-item prop="tokenRefreshSessionSeconds">
        <template #label>
          <span>
            令牌过期刷新时间限制
            <el-tooltip
              content="访问令牌过期后，需在该限定时间内完成令牌刷新，仅【session刷新模式】下有效，适用于web终端，默认30分钟"
              placement="top"
            >
              <Icon icon="ep:question-filled" />
            </el-tooltip>
          </span>
        </template>
        <el-input-number v-model="formData.tokenRefreshSessionSeconds" placeholder="单位：秒" />
      </el-form-item>
      <el-form-item prop="multipleToken">
        <template #label>
          <span>
            多终端同时登录
            <el-tooltip content="用户是否能在多个终端同时登录" placement="top">
              <Icon icon="ep:question-filled" />
            </el-tooltip>
          </span>
        </template>
        <el-radio-group v-model="formData.multipleToken">
          <el-radio v-for="dict in common_bool_type" :key="String(dict.value)" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="授权类型" prop="authorizedGrantTypes">
        <el-select
          v-model="formData.authorizedGrantTypes"
          multiple
          clearable
          placeholder="请选择授权类型"
        >
          <el-option
            v-for="dict in system_oauth2_grant_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="可重定向的 URI 地址" prop="redirectUris">-->
      <!--        <el-input v-model="formData.redirectUris" placeholder="请输入可重定向的 URI 地址" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="授权范围" prop="scopes">-->
      <!--        <el-input v-model="formData.scopes" placeholder="请输入授权范围" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="自动通过的授权范围" prop="autoApproveScopes">-->
      <!--        <el-input v-model="formData.autoApproveScopes" placeholder="请输入自动通过的授权范围" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="权限" prop="authorities">-->
      <!--        <el-input v-model="formData.authorities" placeholder="请输入权限" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="资源" prop="resourceIds">-->
      <!--        <el-input v-model="formData.resourceIds" placeholder="请输入资源" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="附加信息" prop="additionalInformation">-->
      <!--        <el-input v-model="formData.additionalInformation" placeholder="请输入附加信息" />-->
      <!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { OAuth2ClientApi, OAuth2ClientVO } from '@/api/system/oauth2/oauth2_client'
import { FormRules } from 'element-plus'
import { EnableStatusEnum } from '@/utils/constants'

defineOptions({ name: 'SystemOAuth2ClientForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { system_oauth2_grant_type } = useDict(DICT_TYPE.system_oauth2_grant_type)
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)
const { common_bool_type } = useBoolDict(DICT_TYPE.common_bool_type)

const dialogVisible = ref(false) // dialog是否展示
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formDataObj = {
  id: undefined,
  clientId: undefined,
  secret: undefined,
  name: undefined,
  logo: undefined,
  description: undefined,
  status: EnableStatusEnum.Enabled,
  accessTokenValiditySeconds: 1800,
  refreshTokenValiditySeconds: 2592000,
  tokenRefreshSessionSeconds: 1800,
  multipleToken: true,
  authorizedGrantTypes: undefined,
  redirectUris: undefined,
  scopes: undefined,
  autoApproveScopes: undefined,
  authorities: undefined,
  resourceIds: undefined,
  additionalInformation: undefined
}
const formData = ref({ ...formDataObj })
const formRules = reactive<FormRules>({
  clientId: [{ required: true, message: '客户端编号不能为空', trigger: 'blur' }],
  secret: [{ required: true, message: '客户端密钥不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '应用名不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  accessTokenValiditySeconds: [
    {
      required: true,
      message: '访问令牌的有效期不能为空',
      trigger: 'blur'
    }
  ],
  refreshTokenValiditySeconds: [
    {
      required: true,
      message: '刷新令牌的有效期不能为空',
      trigger: 'blur'
    }
  ],
  tokenRefreshSessionSeconds: [
    {
      required: true,
      message: '令牌过期后刷新时间限制不能为空',
      trigger: 'blur'
    }
  ],
  multipleToken: [{ required: true, message: '多终端同时登录不能为空', trigger: 'blur' }],
  authorizedGrantTypes: [{ required: true, message: '授权类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OAuth2ClientApi.getOAuth2Client(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  if (await formValidate(formRef)) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OAuth2ClientVO
    if (formType.value === 'create') {
      await OAuth2ClientApi.createOAuth2Client(data)
      message.success(t('common.createSuccess'))
    } else {
      await OAuth2ClientApi.updateOAuth2Client(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = { ...formDataObj }
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss"></style>
